<?php


namespace Littlexiaoshuishui\Upay\Gateways\Qfpay;

use Littlexiaoshuishui\Upay\Support\Support as Spt;
class Support extends Spt
{
    private static $instance;
    public $rsa;

    public function __construct($config)
    {
        $this->rsa = new Rsa($config['publicKeyPath'],$config['privateKeyPath']);
    }

    public static function create($config)
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**得到数据签名
     * @param $data array
     * @return string
     */
    public function getSign($data){
        $data = $this->argSort($data);
        $mystr = $this->createLinkstring($data);
        $sign = $this->rsa->rsaSign($mystr);
        return $sign;
    }

    public function verify($data, $sign){
        $data = $this->argSort($data);
        $mystr = $this->createLinkstring($data);
        return $this->rsa->rsaCheck($mystr,$sign);
    }

    private function is_assoc($arr) {
        return array_keys($arr) !== range(0, count($arr) - 1);
    }

    public static function argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }

    /**
     * @param $para array
     * return  string
     */
    private function createLinkstring($para){
        $arg = "";
        if (is_array($para)) {
            if ($this->is_assoc($para)) {
                foreach ($para as $value) {
                    $arg .= $this->createLinkstring($value);
                }
            }else{
                $arg .= '[';
                foreach ($para as $value) {
                    $arg .= '"'.$this->createLinkstring($value).'",';
                }
                $arg = substr(  $arg,0,strlen($arg)-1);
                $arg .= ']';
            }

        }else{
            $arg .= $para;
        }
        return $arg;
    }


    public static function namePase($name)
    {
        return ucfirst($name);
    }

}